<template>
    <base-breadcrumb>
        <searchData
                :search-data="searchArr"
                @search="search"
        />
        <a-card>
            <a-spin :spinning="loading1">
            <a-tabs v-model:activeKey="activeKey" @change="tabChange">
                <a-tab-pane :key="item.projectTypeId"
                            :tab="item.projectTypeName"
                            v-for="item in qualityTypes"></a-tab-pane>
            </a-tabs>
            </a-spin>
            <a-row
                    :gutter="10"
                    :style="'height: calc('+GET_REDRESS_PERCENTAGE+'vh - 345px); overflow-y: auto'"
            >
                <a-col :span="4" style="height: 100%">
                    <div style="height: 100%;border-right: 1px solid rgba(215, 215, 215, 1);padding-right: 10px;width: 100%;overflow: hidden;box-sizing: border-box">
                        <a-spin :spinning="loading2" style="height: 100%">
                        <a-tree
                                :expanded-keys="expandedKeys"
                                :auto-expand-parent="autoExpandParent"
                                :tree-data="gData"
                                :selectedKeys.sync="selectedKeys"
                                :replaceFields="{children:'children', title:'fileNo', key:'id' }"
                                @expand="onExpand"
                                @select="selectTreeNode"
                                :style="'maxHeight: calc('+GET_REDRESS_PERCENTAGE+'vh - 380px); overflow: auto'"
                        >
                            <template slot="title" slot-scope="{ fileNo, status }">
                                <div class="ellipsis" :title="fileNo">
                                <span>{{ fileNo }}</span>
                                <span style="color: #ff4d4f">{{!status ? '（停用）': ''}}</span>
                                </div>
                            </template>
                        </a-tree>
                        <div style="display: flex;justify-content: space-around;margin-top: 10px" v-if="hideBuquBtn()">
                            <a-button type="primary" @click="add" size="small" v-btn-permission="'tm_049_add_01'">新增</a-button>
                            <a-button type="primary" @click="edit" size="small" :disabled="!gData.length" v-btn-permission="'tm_049_edi_02'">编辑</a-button>
                            <a-button  v-if="!selectNode.status" @click="updateNode" size="small" :disabled="!gData.length" v-btn-permission="'tm_049_sta_04'">启用</a-button>
                            <a-button type="danger" @click="updateNode" v-else size="small" :disabled="!gData.length" v-btn-permission="'tm_049_sto_03'">停用</a-button>
                        </div>
                        </a-spin>
                    </div>
                </a-col>
                <a-col :span="20">
                    <div class="mb10" v-btn-permission="'tm_049_add_05'">
                        <a-button type="primary" :disabled="loading1 || loading2 || !selectNode.id" @click="addf">添加分项信息</a-button>
                    </div>
                    <list-table
                            ref="table"
                            :row-key="(record) => record.id"
                            :columns="columns"
                            :request="loadData"
                            :is-init="false"
                            :pageKeys="['pageNum', 'pageSize', 'total']"
                    >
                        <template
                                slot="enable"
                                slot-scope="text"
                        >
                            {{ text ? '可用' : '不可用' }}
                        </template>
                        <template slot="action" slot-scope="text,record">
                            <MoreButton>
                                <a @click="view(record)" v-btn-permission="'tm_049_loo_06'">查看</a>
                                <a @click="editf(record)" v-if="hideBuquBtn()" v-btn-permission="'tm_049_edi_07'">编辑</a>
                            </MoreButton>
                        </template>
                    </list-table>
                </a-col>
            </a-row>
        </a-card>
<!--        分类弹窗-->
        <a-modal v-model="nodeVisible"
                 :title="nodeTitle"
                 @ok="handleOk" okText="提交"
                 width="600px"
                 :confirmLoading="loadingBtn1">
            <a-form-model
                    :model="form"
                    :label-col="{ span: 4 }"
                    :wrapper-col="{ span: 14 }"
            >
                <a-row>
                    <a-col :span="12">
                        <a-form-model-item label="文件编号：" class="requiredFormItem">
                            <a-input
                                    v-model="form.fileNo"
                                    :maxLength="20"
                                    placeholder="请输入文件编号"/>
                        </a-form-model-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-model-item  label="状态：" class="requiredFormItem">
                            <a-select v-model="form.status" style="width:100%" placeholder="请选择">
                                <a-select-option :value="1">
                                    可用
                                </a-select-option>
                                <a-select-option :value="0">
                                    不可用
                                </a-select-option>
                            </a-select>
                        </a-form-model-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-model-item label="排序：">
                            <a-input-number
                                    placeholder="请输入排序"
                                    :min="0"
                                    :max="999"
                                    v-model="form.sort"/>
                        </a-form-model-item>
                    </a-col>
                </a-row>

            </a-form-model>
        </a-modal>
<!--        分项信息弹窗-->
        <a-modal v-model="visible"
                 :title="fTitle"
                 width="600px"
                 @cancel="cancel"
                 :confirmLoading="loadingBtn2">
            <a-form-model
                    :model="form2"
                    :label-col="{ span: 4 }"
                    :wrapper-col="{ span: 14 }"
            >
                <a-row>
                    <a-col :span="24">
                        <a-form-model-item label="分项信息：" class="requiredFormItem">
                            <a-textarea
                                    :disabled="disabled"
                                    v-model="form2.partialInfo"
                                    placeholder="请输入分项信息"
                                    :auto-size="{ minRows: 3, maxRows: 5 }"
                                    :maxLength="200"
                            />
                        </a-form-model-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-model-item  label="状态：" class="requiredFormItem">
                            <a-select v-model="form2.status" style="width:100%"  :disabled="disabled">
                                <a-select-option :value="1">
                                    可用
                                </a-select-option>
                                <a-select-option :value="0">
                                    不可用
                                </a-select-option>
                            </a-select>
                        </a-form-model-item>
                    </a-col>
                </a-row>

            </a-form-model>
            <div slot="footer">
                <a-button @click="cancel">取消</a-button>
                <a-button type="primary" @click="handlefOk" v-if="!disabled" :loading="loadingBtn2">提交</a-button>
            </div>
        </a-modal>
    </base-breadcrumb>
</template>

<script>
  import { getProjectTypes } from '@/api/project/projects'
  import {mapGetters } from 'vuex'
  import {
    getTechnicalProgramTypeById,
    addTechnicalProgramType,
    editTechnicalProgramType,
    updateTechnicalProgramType,
    getPageTechnicalProgramTypeInfo,
    addTechnicalProgramTypeInfo,
    editTechnicalProgramTypeInfo
  } from '@/api/technology'
  export default {
    name: 'ClassificationTechnicalSolutions',
    data() {
      return {
        loading1: false,
        loading2: false,
        loadingBtn1: false,
        loadingBtn2: false,
        nodeVisible: false,
        visible: false,
        disabled: false,
        nodeTitle: '新增分类',
        fTitle: "添加分项信息",
        selectedKeys: [],
        selectNode: {},
        form: {
          fileNo: null,
          status: null,
          sort: null
        },
        form2: {
          partialInfo: "",
          status: null
        },
        activeKey: '',
        searchArr: [
          {
            name: '分项名称',
            value: 'partialInfo',
            type: 'input'
          },
        ],
        query: {
          partialInfo: ''
        },
        columns: [
          {
            title: '分项名称',
            dataIndex: 'partialInfo',
          },
          {
            title: '状态',
            dataIndex: 'status',
            scopedSlots: { customRender: 'enable' },
            width: 120,
          },
          {
            title: '操作',
            dataIndex: 'action',
            fixed: 'right',
            scopedSlots: { customRender: 'action' }
          }
        ],
        expandedKeys: [],
        searchValue: '',
        autoExpandParent: true,
        gData: [],
        qualityTypes: []
      }
    },
    computed: {
      ...mapGetters(['GET_REDRESS_PERCENTAGE'])
    },
    mounted() {
      this.getProjectTypes()
    },
    methods: {
      add() {
        this.nodeTitle = "新增分类"
        this.form= {
          fileNo: null,
            status: null,
            sort: null
        }
        this.nodeVisible = true
      },
      edit() {
        this.nodeTitle = "编辑分类"
        this.form = {...this.selectNode, status: this.selectNode.status?1:0}
        this.nodeVisible = true
      },
      handleOk() {
        if(!this.form.fileNo || this.form.status === null) {
          this.$message.warning('请填写完所有必填项信息')
          return
        }
        const data = {
          ...this.form,
          typeId: this.activeKey
        }
        this.loadingBtn1 = true;
        if(this.form.id) {
          editTechnicalProgramType(data).then(res=>{
            this.$message.success('修改成功')
            this.selectNode.name = this.form.fileNo
            this.loadingBtn1 = false
            this.nodeVisible = false
            this.loading2 = true
            this.getTechnicalProgramTypeById()
          })
        } else  {
          addTechnicalProgramType(data).then(res=>{
            this.$message.success('新增成功')
            this.loadingBtn1 = false
            this.nodeVisible = false
            this.loading2 = true
            this.getTechnicalProgramTypeById()
          })
        }

      },
      addf() {
        this.fTitle = '新增分项信息'
        this.form2 = {
          partialInfo: "",
          status: null
        }
        this.disabled = false
        this.visible = true
      },
      editf(row) {
        this.disabled = false
        this.fTitle = '编辑分项信息'
        this.form2 = {...row, status: row.status?1:0}
        this.visible = true
      },
      view(row) {
        this.fTitle = '查看分项信息'
        this.form2 = {...row, status: row.status?1:0}
        this.visible = true
        this.disabled = true
      },
      cancel() {
        this.loadingBtn2 = false
        this.visible = false
      },
      // 分项信息点击ok
      handlefOk() {
        if(!this.form2.partialInfo || this.form2.status===null) {
          this.$message.warning('请填写完所有必填项信息')
          return
        }
        this.loadingBtn2 = true
        const data = {...this.form2, programTypeId: this.selectNode.id}
        if(this.form2.id) {
          editTechnicalProgramTypeInfo(data).then(res => {
            this.loadingBtn2 = false
            this.visible = false
            this.disabled = false
            this.$message.success('修改成功')
            this.$refs.table.refresh(true)
          })
        } else {
          addTechnicalProgramTypeInfo(data).then(res => {
            this.loadingBtn2 = false
            this.visible = false
            this.disabled = false
            this.$message.success('新增成功')
            this.$refs.table.refresh(true)
          })
        }
      },
      updateNode() {
        const fn = () => {
          this.loading2 = true
          const data = {
            ...this.selectNode,
            status: !this.selectNode.status
          }
          updateTechnicalProgramType(data).then(res=>{
            this.$message.success(!this.selectNode.status ? '启用成功': '停用成功')
            this.selectNode.status = !this.selectNode.status
            this.getTechnicalProgramTypeById()
          })
        }

        if(this.selectNode.status) {
          this.$confirm({
            title: '提示',
            content: '停用该节点时会同时停用该节点下的分项信息，确认是否停用？',
            onOk() {
              fn()
            },
            onCancel() {},
          });
        } else {
          fn()
        }
      },
      getProjectTypes(isRefresh=false) {
        this.loading1 = true
        this.loading2 = true
        getProjectTypes().then((res) => {
          this.qualityTypes = res.data?.filter(i => i.status*1 === 1)
          this.loading1 = false
          if(isRefresh) {
            this.loading2 = false
          } else {
            this.activeKey = this.qualityTypes[0].projectTypeId
            this.getTechnicalProgramTypeById(true)
          }
        })
      },
      getTechnicalProgramTypeById(isInit = false) {
        const data = {
          pageNum: 1,
          pageSize: 9999999,
          param: {
            typeId: this.activeKey
          }
        }
        getTechnicalProgramTypeById(data).then(res=>{
          this.loading2 = false
          if(res.data.list.length) {
            this.generateList(res.data.list)
            this.gData = res.data.list
            if(isInit) {
              this.selectedKeys = [res.data.list[0].id]
              this.selectNode = res.data.list[0]
            }
          } else {
            this.gData = []
            this.selectedKeys = []
            this.selectNode = {}
          }
          this.$refs.table.refresh(true)
        })
      },
      loadData(parameter) {
        if(!this.selectNode.id) {
          return Promise.resolve({
            code: '0',
            data: {
              totalSize: 0,
              list: []
            }
          })
        }
        const requestParameters = Object.assign({}, parameter, {
          param: {
            programTypeId: this.selectNode.id ,
            ...this.query
          }
        })
        return getPageTechnicalProgramTypeInfo(requestParameters).then(res=>{
          res.data.totalSize = res.data.total
          return res
        })
      },
      search(val) {
        this.query = val
        this.getProjectTypes(true)
        this.$refs.table.refresh(true)
      },
      tabChange() {
        this.loading2 = true
        this.getTechnicalProgramTypeById(true)
      },
      onExpand(expandedKeys) {
        this.expandedKeys = expandedKeys;
        this.autoExpandParent = false;
      },
      selectTreeNode(selectedKeys, { node}) {
        this.selectedKeys = selectedKeys
        this.selectNode = {...node.dataRef}
        this.$refs.table.refresh(true)
      },
      generateList(data) {
        for (let i = 0; i < data.length; i++) {
          const node = data[i];
          node.scopedSlots = { title: 'title'}
          if (node.children) {
            this.generateList(node.children);
          }
        }
      },
    }
  }
</script>

<style scoped>
    .ellipsis {
        max-width: 100%;
        overflow: hidden;
        text-overflow: ellipsis;
        word-break: break-all;
        white-space: nowrap;
    }
</style>